﻿<%@ WebHandler Language="C#" Class="ajaxorder" %>

using System;
using System.Web;
using System.Web.SessionState;
using GZ.Entity;
using Newtonsoft.Json;
using GZ.Common;
using System.Text.RegularExpressions;
using System.Text;
using System.Data;
using System.IO;
/// <summary>
/// 订单ajax处理方法
/// </summary>
public class ajaxorder : IHttpHandler, IRequiresSessionState
{
    HttpRequest Request;
    HttpResponse Response;
    HttpSessionState Session;
    HttpServerUtility Server;
    HttpCookieCollection Cookie;
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            Request = context.Request;
            Response = context.Response;
            Session = context.Session;
            Server = context.Server;
            Cookie = context.Request.Cookies;
            string method = Request["methodName"].ToString();
            System.Reflection.MethodInfo methodInfo = this.GetType().GetMethod(method);
            methodInfo.Invoke(this, null);

        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
    }

    /// <summary>
    /// 前台客户订单联系方式
    /// </summary>
    public void InitialCustomerOrderContact()
    {
        if (Request.Cookies["gz_customer"] != null)
        {
            string user = Request.Cookies["gz_customer"].Value;
            if (!String.IsNullOrEmpty(user))
            {
                CookieUserObject userObj = JsonConvert.DeserializeObject<CookieUserObject>(user);
                ECustomer customerAccessor = new ECustomer();
                ECustomer customerModel = customerAccessor.GetCustomerById(Convert.ToInt32(userObj.Id));
                if (customerModel != null)
                {
                    Response.Write(JsonConvert.SerializeObject(customerModel));
                }
            }
        }
    }
    /// <summary>
    /// 前台验证客户提交订单的配货时间
    /// </summary>
    public void ValidateDeliveryPeriodDate()
    {
        String date = Request.QueryString["date"];

        if (!String.IsNullOrEmpty(date))
        {
            Response.Write(new EDeliveryPeriod().IsEffective(Convert.ToDateTime(date), Convert.ToInt32(Request.QueryString["PeriodId"])) ? "true" : "false");
        }
        else
        {
            Response.Write("dz_datenull");
        }
    }

    /// <summary>
    /// 前台客户历史订单列表
    /// </summary>
    public void QuerySingleCustomerHistoryOrders()
    {

    }
    /// <summary>
    /// 前台提交订单
    /// </summary>
    public void SubmitCustomerOrder()
    {
        try
        {
            ECustomer customerAccessor = new ECustomer();
            HttpCookie cookie = Request.Cookies["gz_customer"];
            CookieUserObject userObj = null;
            ECustomer customerModel = null;
            bool isOnTimeBuy = false;

            string date = Request["txt_DeliveryDate"];
            string perid = Request["sel_DeliveryPeriodId"];

            bool isValidatePerDate = new EDeliveryPeriod().IsEffective(Convert.ToDateTime(date), Convert.ToInt32(perid));

            if (!isValidatePerDate)
            {
                Response.Write("【您好,为了给工作人员留出制作与配送的时间,请您选择下一个配送时段:)我们会为您奉上一杯完美制作的果汁饮品!】");
                return;
            }

            if (!ValidateCartIsHaveProducts())
            {
                Response.Write("gz_您的购物车目前没有商品')");
                return;
            }

            #region 客户信息初始化，当用户没有登录的时候，把表单信息作为注册信息，否则直接读取登录cookie中的用户信息提交订单


            customerModel = new ECustomer();

            customerModel.CustomerName = Request.QueryString["txt_CustomerName"];
            customerModel.TelNum = Request.QueryString["txt_TelNum"];
            customerModel.Email = Request.QueryString["txt_Email"];

            customerModel.RegionId = Convert.ToInt32(Request.QueryString["sel_RegionId"]);
            customerModel.BusinessDistrictId = Convert.ToInt32(Request.QueryString["sel_BusinessDistrictId"]);
            customerModel.OfficeId = Convert.ToInt32(Request.QueryString["sel_OfficeId"]);
            customerModel.FloorId = Convert.ToInt32(Request.QueryString["sel_FloorId"]);
            customerModel.Memo = String.Empty; // !String.IsNullOrEmpty(Request.QueryString["txt_Memo"]) ? Request.QueryString["txt_Memo"] : "这家伙很懒，什么都没写!";
            customerModel.Address = Request.QueryString["txt_Address"];

            Int32 customerId = 0;
            bool isSuccess = false;
            if (cookie == null)
            {
                if (!String.IsNullOrEmpty(Request.QueryString["txt_Pwd"]) && !String.IsNullOrEmpty(Request.QueryString["txt_Email"]))
                {
                    cookie = new HttpCookie("gz_customer");
                    customerModel.Pwd = SecurityEncryption.MD5(Request.QueryString["txt_Pwd"], 16);
                    customerId = customerAccessor.Insert(customerModel);
                }
                else
                {
                    isOnTimeBuy = true;
                    isSuccess = true;
                }
                //非一次性购买方式
                if (!isOnTimeBuy)
                {
                    if (customerId > 0)
                    {
                        userObj = new CookieUserObject(customerId.ToString(), HttpUtility.UrlEncode(customerModel.CustomerName), customerModel.Email);
                        userObj.RegionId = customerModel.RegionId.ToString();
                        userObj.BusinessDistrictId = customerModel.BusinessDistrictId.ToString();
                        userObj.OfficeId = customerModel.OfficeId.ToString();
                        userObj.FloorId = customerModel.FloorId.ToString();
                        cookie.Value = JsonConvert.SerializeObject(userObj);
                        cookie.Expires = DateTime.MaxValue;
                        Response.Cookies.Add(cookie);
                        isSuccess = true;
                    }
                    else
                    {
                        isSuccess = false;
                    }
                }
            }
            else
            {

                userObj = JsonConvert.DeserializeObject<CookieUserObject>(Request.Cookies["gz_customer"].Value);

                customerModel = customerAccessor.GetCustomerById(Convert.ToInt32(userObj.Id));
                customerModel.CustomerName = Request.QueryString["txt_CustomerName"];
                customerModel.TelNum = Request.QueryString["txt_TelNum"];
                customerModel.Email = Request.QueryString["txt_Email"];
                customerModel.RegionId = Convert.ToInt32(Request.QueryString["sel_RegionId"]);
                customerModel.BusinessDistrictId = Convert.ToInt32(Request.QueryString["sel_BusinessDistrictId"]);
                customerModel.OfficeId = Convert.ToInt32(Request.QueryString["sel_OfficeId"]);
                customerModel.FloorId = Convert.ToInt32(Request.QueryString["sel_FloorId"]);
                customerModel.Memo = String.Empty;// !String.IsNullOrEmpty(Request.QueryString["txt_Memo"]) ? Request.QueryString["txt_Memo"] : "这家伙很懒，什么都没写!";
                customerModel.Address = Request.QueryString["txt_Address"];

                customerId = Convert.ToInt32(userObj.Id);
                userObj.Name = HttpUtility.UrlEncode(Request.QueryString["txt_CustomerName"]);
                userObj.Email = Request.QueryString["txt_Email"];
                userObj.RegionId = Request.QueryString["sel_RegionId"];
                userObj.BusinessDistrictId = Request.QueryString["sel_BusinessDistrictId"];
                userObj.OfficeId = Request.QueryString["sel_OfficeId"];
                userObj.FloorId = Request.QueryString["sel_FloorId"];
                cookie.Value = JsonConvert.SerializeObject(userObj);
                cookie.Expires = DateTime.MaxValue;
                Response.Cookies.Add(cookie);
                isSuccess = customerAccessor.Update(customerModel);
            }

            #endregion

            if (isSuccess)
            {
                try
                {
                    #region 提交订单

                    EOrder orderAccessor = new EOrder();
                    EOrder orderModel = new EOrder();
                    orderModel.Email = customerModel.Email;
                    orderModel.CustomerId = isOnTimeBuy ? 0 : Convert.ToInt32(userObj.Id);
                    orderModel.CustomerName = Request.QueryString["txt_CustomerName"];
                    orderModel.TelNum = customerModel.TelNum;
                    orderModel.RegionId = customerModel.RegionId;
                    orderModel.BusinessDistrictId = customerModel.BusinessDistrictId;
                    orderModel.OfficeId = customerModel.OfficeId;
                    orderModel.FloorId = customerModel.FloorId;
                    orderModel.Address = customerModel.Address;
                    orderModel.CreateDate = DateTime.Now;
                    //付款类型
                    string paytype = Request.QueryString["pay_type"];
                    if (paytype == "货到付款")
                    {
                        orderModel.PaymentType = 1;
                    }
                    else
                    {
                        //如果线上支付 的话，线上类型
                        string pay_class = Request.QueryString["pay_class"];
                        switch (pay_class)
                        {
                            case "财付通":
                                orderModel.PaymentType = 2;
                                break;
                            case "支付宝":
                                orderModel.PaymentType = 3;
                                break;
                            default:
                                orderModel.PaymentType = 1;
                                break;
                        }
                    }



                    if (!String.IsNullOrEmpty(Request.QueryString["txt_OrderMemo"]) && Request.QueryString["txt_OrderMemo"] != "如：常温、冰镇等口味偏好")
                    {
                        orderModel.Memo = Request.QueryString["txt_OrderMemo"];
                    }
                    else
                    {
                        orderModel.Memo = "这家伙很懒，什么都没写!";
                    }
                    orderModel.DeliveryPeriodId = Convert.ToInt32(Request.QueryString["sel_DeliveryPeriodId"]);
                    orderModel.DeliveryDate = Convert.ToDateTime(Request.QueryString["txt_DeliveryDate"]);
                    orderModel.OrderAmount = Convert.ToDecimal(Request.Cookies["Amount"].Value);
                    long orderId = orderAccessor.Insert(orderModel);

                    #endregion

                    #region 订单明细

                    if (orderId > 0)
                    {
                        //如果订单总价为0，根据购物车中订单明细计算实际订单总价更新当前总价为0的订单
                        if (orderModel.OrderAmount == 0)
                        {
                            orderAccessor.UpdateOrderAmountByOid(orderId, CalcuateAmountAgain());
                        }

                        EOrderDetail orderDetailAccessor = new EOrderDetail();
                        String c = CurrentCart;
                        if (!String.IsNullOrEmpty(c))
                        {
                            EOrderDetail orderDetailModel = null;
                            String[] carts = c.Split(new char[] { '&' });
                            int currentCnt = 0;
                            decimal totalAmt = 0;
                            foreach (String cart in carts)
                            {
                                String[] cartItems = cart.Split((new char[] { '|' }));
                                currentCnt = Convert.ToInt32(cartItems[1]);
                                if (currentCnt != 0)
                                {
                                    orderDetailModel = new EOrderDetail();
                                    orderDetailModel.OrderId = orderId;
                                    orderDetailModel.Price = Convert.ToDecimal(cartItems[2]);
                                    orderDetailModel.ProductId = Convert.ToInt32(cartItems[0].Split(new char[] { '=' })[0]);
                                    orderDetailModel.Cnt = currentCnt;
                                    orderDetailModel.Amount = (Convert.ToDecimal(cartItems[2])) * Convert.ToInt32(cartItems[1]);
                                    totalAmt += orderDetailModel.Amount;
                                    orderDetailAccessor.Insert(orderDetailModel);
                                }
                            }

                            //获取当前成功订单金额
                            decimal _outAmt = orderAccessor.GetOrderAmountByOrderId(orderId);
                            bool isUpdate = false;
                            //当返订单总金额为0时，通过当前订单明细价格更新当前订单为0的订单金额
                            if (_outAmt != totalAmt)
                            {
                                isUpdate = orderAccessor.UpdateOrderAmountByOid(orderId, totalAmt);
                            }

                            //清空购物车
                            cookie = Request.Cookies["carList"];
                            cookie.Expires = DateTime.Now.AddDays(-1);
                            Response.Cookies.Add(cookie);

                            cookie = Request.Cookies["Amount"];
                            cookie.Expires = DateTime.Now.AddDays(-1);
                            Response.Cookies.Add(cookie);

                            cookie = Request.Cookies["totalCates"];
                            cookie.Expires = DateTime.Now.AddDays(-1);
                            Response.Cookies.Add(cookie);

                            cookie = new HttpCookie("deliveryDate");
                            // cookie.Expires = DateTime.Now.AddMinutes(1);
                            System.Data.DataRow row = new EDeliveryPeriod().GetDeliveryPeriod().Select(" id=" + Request.QueryString["sel_DeliveryPeriodId"])[0];
                            cookie.Value = HttpUtility.UrlEncode(Request.QueryString["txt_DeliveryDate"] + "日" + row["DeliveryPeriodName"].ToString(), Encoding.UTF8);
                            Response.Cookies.Add(cookie);
                            Int32 OrderAmount = Convert.ToInt32(totalAmt);
                            Response.Write("订单成功," + orderId + "," + OrderAmount);


                            WriteOrderLog(orderId, orderModel.OrderAmount, totalAmt, isUpdate);
                        }
                    }
                    else
                    {
                        Response.Write("提交订单发生异常,请联系客服下单!");
                    }

                    #endregion
                }
                catch (Exception ex)
                {
                    Response.Write("gz_提交订单发生异常,请联系客服下单!");
                }
            }
            else
            {
                Response.Write("gz_提交订单发生异常,请联系客服下单!");
            }
        }
        catch (Exception ex)
        {


        }
    }
    /// <summary>
    /// 如果订单总价为0，根据购物车中订单明细计算实际订单总价更新之
    /// </summary>
    /// <returns></returns>
    private decimal CalcuateAmountAgain()
    {
        decimal _amount = 0;
        String c = CurrentCart;
        if (!String.IsNullOrEmpty(c))
        {
            String[] carts = c.Split(new char[] { '&' });
            int currentCnt = 0;
            foreach (String cart in carts)
            {
                String[] cartItems = cart.Split((new char[] { '|' }));
                currentCnt = Convert.ToInt32(cartItems[1]);
                if (currentCnt != 0)
                {
                    _amount += (Convert.ToDecimal(cartItems[2])) * Convert.ToInt32(cartItems[1]);
                }
            }
        }
        return _amount;
    }

    public void WriteOrderLog(long oid, decimal oAmount, decimal odetAmount, bool isUpdate)
    {
        if (Directory.Exists(Server.MapPath("/log/")))
        {
            Directory.CreateDirectory(Server.MapPath("/log/"));
        }
        string path = Server.MapPath("/log/log_" + DateTime.Now.Month + ".txt");

        using (StreamWriter writer = new StreamWriter(path, true))
        {
            writer.WriteLine(string.Format("订单产生日期：{0} 订单号：{1} 订单总价：{2} 明细总价：{3} 是否更新总价：{4}", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"), oid, oAmount, odetAmount, isUpdate));
        }
    }

    /// <summary>
    /// 购物车中是否有商品购买数量
    /// </summary>
    /// <returns></returns>
    public bool ValidateCartIsHaveProducts()
    {
        if (String.IsNullOrEmpty(CurrentCart))
        {
            return false;
        }
        else
        {
            if (CurrentCart.IndexOf("&") > -1)
            {
                int t = 0;
                String[] carts = CurrentCart.Split(new char[] { '&' });

                for (int i = 0; i < carts.Length; i++)
                {
                    if (carts[i].Split(new char[] { '|' })[1] == "0")
                    {
                        t++;
                    }
                }
                if (t == carts.Length)
                {
                    return false;
                }
            }
            else
            {
                if (CurrentCart.Split(new char[] { '|' })[1] == "0")
                {
                    return false;
                }
            }
        }
        return true;
    }

    /// <summary>
    /// 完成订单
    /// </summary>
    public void CompleteOrder()
    {
        Int64 OrderId = Convert.ToInt64(Request.QueryString["orderid"]);
        Decimal ActualAmount = Convert.ToDecimal(Request.QueryString["actualamount"]);
        string txtDeliveryRemark = Request.QueryString["txtDeliveryRemark"].ToString();
        EOrder obj = new EOrder();
        if (obj.CompleteOrder(OrderId, ActualAmount, txtDeliveryRemark))
        {
            Response.Write("ok");
        }
        else
        {
            Response.Write("no");
        }

    }

    /// <summary>
    /// 打印订单
    /// </summary>
    public void PrintOrder()
    {
        Int64 OrderId = Convert.ToInt64(Request.QueryString["orderid"]);
        EOrder obj = new EOrder();
        if (obj.PrintOrder(OrderId))
        {
            Response.Write("ok");
        }
        else
        {
            Response.Write("no");
        }
    }

    public String CurrentCart
    {
        get
        {
            if (Request.Cookies["carList"] != null)
            {
                return Request.Cookies["carList"].Value;
            }
            return String.Empty;
        }
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}